package com.example.myactspringboot.server;

import com.example.myactspringboot.bean.*;
import com.example.myactspringboot.dao.BusiTaskMainMapper;
import com.example.myactspringboot.dao.SysUserMapper;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.jws.Oneway;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Create 2023-09-16 15:25
 * @Description
 */
@Service
public class BusiTaskMainService {
    @Autowired
    private BusiTaskMainMapper busiTaskMainMapper;
    @Autowired
    private TaskService taskService;
    @Autowired
    HistoryService historyService;
    @Autowired
    SysUserMapper userMapper;
    @Autowired
    RuntimeService runtimeService;

    public int saveMain(BusiTaskMain busiTaskMain){
        return busiTaskMainMapper.saveOne(busiTaskMain);
    }

    public List<BusiTaskMainVo> getAllTaskMain(BusiTaskMain busiTaskMain){
        List<BusiTaskMain> allTaskMain = busiTaskMainMapper.getAllTaskMain(busiTaskMain);
        List<BusiTaskMainVo> busiTaskMainVoList = new ArrayList<>();
        for (BusiTaskMain taskMain : allTaskMain) {
            BusiTaskMainVo busiTaskMainVo = new BusiTaskMainVo();
            BeanUtils.copyProperties(taskMain,busiTaskMainVo);
            // 当前环节
            if (StringUtils.isNotBlank(busiTaskMainVo.getInstanceId())) {
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(busiTaskMainVo.getInstanceId())
//                        .singleResult();
                        .list();    // 例如请假会签，会同时拥有多个任务
                if (!CollectionUtils.isEmpty(taskList)) {
                    TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
                    busiTaskMainVo.setTaskId(task.getId());
                    if (task.getSuspensionState() == 2) {
                        busiTaskMainVo.setTaskName("已挂起");
                        busiTaskMainVo.setSuspendState("2");
                    } else {
                        busiTaskMainVo.setTaskName(task.getName());
                        busiTaskMainVo.setSuspendState("1");
                    }
                } else {
                    // 已办结或者已撤销
                    busiTaskMainVo.setTaskName("已结束");
                }
            } else {
                busiTaskMainVo.setTaskName("未启动");
            }
            busiTaskMainVoList.add(busiTaskMainVo);
        }
//        List<BusiTaskMainVo> collect = busiTaskMainVoList.stream().filter(item -> "已结束".equals(item.getTaskName())).collect(Collectors.toList());
        return busiTaskMainVoList;
    }

    public int updateMain(BusiTaskMain busiTaskMain){
        return busiTaskMainMapper.updateMain(busiTaskMain);
    }
    public BusiTaskMain getById(int id){
        BusiTaskMain byId = busiTaskMainMapper.getById(id);
        return byId;
    }

    public int  saveTodoItem(String instanceId,String title, String reason, String type,String name){
        BusiTaskNode todoItem = new BusiTaskNode();
        todoItem.setItemName(title);
        todoItem.setItemContent(reason);
        todoItem.setIsView("0");
        todoItem.setIsHandle("0");
        todoItem.setModule(type);
        todoItem.setTodoTime(new Date());
        todoItem.setInstanceId(instanceId);
        todoItem.setHandleUserName(name);
        todoItem.setHandleUserId(name);
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(instanceId).active().list();
       int count =0;
        for (Task task : taskList) {
            BusiTaskNode newItem = new BusiTaskNode();
            BeanUtils.copyProperties(todoItem,newItem);
            newItem.setTaskId(task.getId());
            newItem.setTaskName("task" + task.getTaskDefinitionKey().substring(0, 1).toUpperCase() + task.getTaskDefinitionKey().substring(1));
            newItem.setNodeName(task.getName());
            int i = busiTaskMainMapper.saveTodoItem(newItem);
            count+=i;
        }
//        return busiTaskMainMapper.saveTodoItem(todoItem);
        return count;
    }
    @Transactional
    public int complete(Map map,String name){
        String taskId = map.get("taskId").toString();
        List<BusiTaskNode> busiTaskNodes = busiTaskMainMapper.getTaskNodeList(taskId,name);
        String isPass = map.get("isPass") == null ? "" : map.get("isPass").toString();
        String manageOpinion = map.get("manageOpinion")==null?"":map.get("manageOpinion").toString();
        String instanceId = map.get("instanceId") == null ? "" : map.get("instanceId").toString();
        String todoManId = map.get("todoManId") == null ? "" : map.get("todoManId").toString();
        for (BusiTaskNode busiTaskNode : busiTaskNodes) {
            if (!"".equals(isPass)){
                busiTaskNode.setIsPass(map.get("isPass").toString());
            }

            if (!"".equals(manageOpinion)){
                busiTaskNode.setManageOpinion(manageOpinion);
            }
            //下一个要办理的人
            if (!"".equals(todoManId)){
                busiTaskNode.setTodoUserId(todoManId);
                busiTaskNode.setTodoUserName(todoManId);
            }
            busiTaskNode.setHandleTime(new Date());
            busiTaskNode.setIsView("1");
            busiTaskNode.setIsHandle("1");
            busiTaskMainMapper.updateBusiTaskNode(busiTaskNode);
            System.out.println(busiTaskNode);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        if (!"".equals(todoManId)) {
            hashMap.put("jingli", todoManId);
        }
        taskService.addComment(taskId, instanceId, isPass+manageOpinion);
        taskService.complete(taskId,hashMap);
        int i = saveTodoItem(instanceId, map.get("title").toString(), map.get("reason").toString(), "test1", todoManId);
        return i;
    }

    //历史记录
    public List<HistoricActivity> getHisData(String instanceId){

        List<HistoricActivity> activityList = new ArrayList<>();

        //.activityType("userTask")   userTask 是act_hi_actinst表里的字段
        HistoricActivityInstanceQuery hisquery = historyService.createHistoricActivityInstanceQuery();
        //.finished()  条件已完成    .orderByHistoricActivityInstanceStartTime().asc()
        List<HistoricActivityInstance> hislist = hisquery.processInstanceId(instanceId).list();

        //将id排序并处理为空情况，nullsLast是值将空值放最后，nullsFirst同理
        hislist =  hislist.stream().sorted(Comparator.comparing(HistoricActivityInstance::getEndTime, Comparator.nullsLast(Date::compareTo)))
                .collect(Collectors.toList());

        hislist.forEach(instance -> {
            HistoricActivity activity = new HistoricActivity();
            BeanUtils.copyProperties(instance, activity);
            String taskId = instance.getTaskId();
/*            List<Comment> comment = taskService.getTaskComments(taskId, "comment");
            if (!CollectionUtils.isEmpty(comment)) {
                activity.setComment(comment.get(0).getFullMessage());
            }*/
            SysUser sysUser = userMapper.getUserByName(instance.getAssignee());
            if (sysUser != null) {
                activity.setAssigneeName(sysUser.getName());
                BusiTaskNode busiTaskNode = busiTaskMainMapper.gettaskNode(instance.getTaskId());
                System.out.println(busiTaskNode);
            }else {
                BusiTaskMain busiTaskMain = busiTaskMainMapper.getByInstanceId(instance.getProcessInstanceId());
                activity.setAssigneeName(busiTaskMain.getApplyUser());
            }
            activityList.add(activity);
        });
  /*      for (HistoricActivity historicActivity : activityList) {
            System.out.println(historicActivity);
        }*/

        return activityList;
    }

    /**
     * 已办任务
     */
    public List<BusiTaskMainVo> getDoneData(){
        Session session = SecurityUtils.getSubject().getSession();
        String username = (String) session.getAttribute("username");
//        通过HistoryService的createHistoricTaskInstanceQuery（）方法，就可以得到HistoricTaskInstanceQuery对象，主要用来根据查询条件，到历史任务表ACT_HI_TASKINST中查询符合条件的数据
       List<BusiTaskMainVo> mainVos = new ArrayList<>();
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .processDefinitionKey("test1")
                .taskAssignee(username)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();
        for (HistoricTaskInstance historicTaskInstance : list) {
            if ("用户撤销".equals(historicTaskInstance.getDeleteReason())){
                continue;
            }
            String processInstanceId = historicTaskInstance.getProcessInstanceId();
//            使用HistoryService的createHistoricProcessInstanceQuery（）方法就可以得到HistoricProcessInstanceQuery对象，该对象主要用于流程实例的历史数据查询。对于流程实例，不管流程是否完成，都会保存到ACT_HI_PROCINST表中
            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            BusiTaskMain busiTaskMain = busiTaskMainMapper.getById(new Integer(businessKey));
            BusiTaskMainVo busiTaskMainVo = new BusiTaskMainVo();
            BeanUtils.copyProperties(busiTaskMain,busiTaskMainVo);
//            System.out.println(busiTaskMain);
            busiTaskMainVo.setTaskName(historicTaskInstance.getName());
            mainVos.add(busiTaskMainVo);
        }
        return mainVos;
    }

    public void cancelApply(String instanceId, String deleteReason) {
        // 执行此方法后未审批的任务 act_ru_task 会被删除，流程历史 act_hi_taskinst 不会被删除，并且流程历史的状态为finished完成
        runtimeService.deleteProcessInstance(instanceId, deleteReason);
    }
}
